package com.farm.wcp.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.farm.authority.service.OutuserServiceInter;
import com.farm.authority.service.UserServiceInter;
import com.farm.cbtg.service.AppcatalogServiceInter;
import com.farm.configer.domain.ex.ConfigerMetaPara;
import com.farm.configer.form.ConfigerFormGenerator;
import com.farm.configer.form.FormModel;
import com.farm.configer.form.FormModelUtils;
import com.farm.core.page.ViewMode;
import com.farm.project.domain.Project;
import com.farm.project.domain.ProjectActive;
import com.farm.project.domain.Tasknode;
import com.farm.project.service.ProjectServiceInter;
import com.farm.project.service.TasknodeServiceInter;
import com.farm.sfile.WdapFileServiceInter;
import com.farm.template.domain.Template;
import com.farm.template.domain.TemplateDir;
import com.farm.template.domain.TemplateFile;
import com.farm.template.domain.ex.SysDir;
import com.farm.template.domain.ex.SysFile;
import com.farm.template.service.TemplateServiceInter;
import com.farm.template.service.TemplatedirServiceInter;
import com.farm.template.service.TemplatefileServiceInter;
import com.farm.template.utils.FarmJsonUtils;
import com.farm.template.utils.FreeMarkerUtils;
import com.farm.wcp.util.ThemesUtil;
import com.farm.web.WebUtils;

@RequestMapping("/prorun")
@Controller
public class ProjectWebController extends WebUtils {
	private final static Logger log = Logger.getLogger(ProjectWebController.class);
	@Resource
	private OutuserServiceInter outUserServiceImpl;
	@Resource
	private UserServiceInter userServiceImpl;
	@Resource
	private WdapFileServiceInter wdapFileServiceImpl;
	@Resource
	private TemplateServiceInter templateServiceImpl;
	@Resource
	private TemplatedirServiceInter templateDirServiceImpl;
	@Resource
	private TemplatefileServiceInter templateFileServiceImpl;
	@Resource
	private ProjectServiceInter projectServiceImpl;
	@Resource
	private AppcatalogServiceInter appCatalogServiceImpl;
	@Resource
	private TasknodeServiceInter taskNodeServiceImpl;

	/**
	 * 运行生成项目
	 * 
	 * @return
	 */
	@RequestMapping("/index")
	public ModelAndView pubLogin(String activeid, String pagemodel, HttpSession session, HttpServletRequest request) {
		ViewMode mode = ViewMode.getInstance();
		try {
			ProjectActive active = projectServiceImpl.getActive(activeid);
			Project project = projectServiceImpl.getProjectEntity(active.getProjectid());

			return mode.putAttr("project", project).putAttr("active", active).putAttr("pagemodel", pagemodel)
					.returnModelAndView(ThemesUtil.getThemePath() + "/project/run-index");
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e)
					.returnModelAndView(ThemesUtil.getThemePath() + "/simple-500");
		}
	}

	/**
	 * 删除
	 * 
	 * @return
	 */
	@RequestMapping("/delActive")
	public ModelAndView delActive(String activeid, HttpSession session, HttpServletRequest request) {
		ViewMode mode = ViewMode.getInstance();
		try {
			ProjectActive active = projectServiceImpl.getActive(activeid);
			projectServiceImpl.delActive(active.getId());
			return mode.returnRedirectUrl("/prorun/actives.do?projectid=" + active.getProjectid());
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e)
					.returnModelAndView(ThemesUtil.getThemePath() + "/simple-500");
		}
	}

	/**
	 * 加载当前任务表单
	 * 
	 * @param activeid
	 * @param session
	 * @param request
	 * @return
	 */
	@RequestMapping("/loadForm")
	public ModelAndView configerform(String activeid, HttpSession session, HttpServletRequest request) {
		ViewMode mode = ViewMode.getInstance();
		try {
			ProjectActive active = projectServiceImpl.getActive(activeid);
			Project project = projectServiceImpl.getProjectEntity(active.getProjectid());

			if (active.getNodeid().equals("START")) {
				return mode.putAttr("project", project).putAttr("active", active)
						.returnModelAndView(ThemesUtil.getThemePath() + "/project/common/form-start");
			}
			if (active.getNodeid().equals("END")) {
				return mode.putAttr("project", project).putAttr("active", active)
						.returnModelAndView(ThemesUtil.getThemePath() + "/project/common/form-end");
			}
			Tasknode node = taskNodeServiceImpl.getTasknodeEntity(active.getNodeid());

			if (node == null) {
				throw new RuntimeException("当前任务不存在，请选择其他任务：taskNodeId-" + active.getNodeid());
			}

			if (node.getModel().equals("configer")) {
				return mode.putAttr("project", project).putAttr("active", active).returnRedirectOnlyUrl(
						"/confweb/baseForm.do?configerid=" + node.getRid() + "&activeid=" + activeid);
			}
			if (node.getModel().equals("template")) {
				Tasknode tnode = taskNodeServiceImpl.getTasknodeEntity(active.getNodeid());
				Template template = templateServiceImpl.getTemplateEntity(tnode.getRid());
				return mode.putAttr("project", project).putAttr("template", template).putAttr("active", active)
						.putAttr("node", tnode)
						.returnModelAndView(ThemesUtil.getThemePath() + "/project/common/form-templete");
			}

			return mode.putAttr("project", project).putAttr("active", active).putAttr("node", node)
					.returnModelAndView(ThemesUtil.getThemePath() + "/project/common/form-none");

		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e)
					.returnModelAndView(ThemesUtil.getThemePath() + "/project/common/form-message");
		}
	}

	/**
	 * 参数提交表单
	 * 
	 * @param activeid
	 * @param paras
	 * @param session
	 * @return
	 */
	@RequestMapping("/submitForm")
	@ResponseBody
	public Map<String, Object> submitForm(String activeid, String paras, HttpSession session) {
		try {
			ViewMode page = ViewMode.getInstance();
			ProjectActive active = projectServiceImpl.getActive(activeid);
			if (active.getNodeid().equals("START") || active.getNodeid().equals("END")) {

			} else {
				Tasknode node = taskNodeServiceImpl.getTasknodeEntity(active.getNodeid());
				if (node.getModel().equals("configer")) {
					FormModel formmodel = ConfigerFormGenerator.getConfigerModelInstance(node.getRid());
					List<ConfigerMetaPara> paraList = FormModelUtils.formatParas(node.getRid(), paras);
					Map<String, Object> configParas = formmodel.submitForm(paraList);
					for (Entry<String, Object> para : configParas.entrySet()) {
						String key = para.getKey();
						String json = FormModelUtils.formatObjTojson(para.getValue());
						projectServiceImpl.saveActiveParameters(activeid, key, json, getCurrentUser(session));
					}
				}
			}
			projectServiceImpl.toDoNextTaskNode(activeid);
			return page.returnObjMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 获取参数变量
	 * 
	 * @param activeid
	 * @param paras
	 * @param session
	 * @return
	 */
	@RequestMapping("/loadActiveAttrs")
	@ResponseBody
	public Map<String, Object> loadActiveAttrs(String activeid, HttpSession session) {
		try {
			ViewMode page = ViewMode.getInstance();
			Map<String, Object> paras = projectServiceImpl.getActiveConfigerMap(activeid);
			return page.putAttr("json", FormModelUtils.formatObjTojson(paras)).returnObjMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 获取参数变量
	 * 
	 * @param activeid
	 * @param paras
	 * @param session
	 * @return
	 */
	@RequestMapping("/loadActiveDebugInfo")
	@ResponseBody
	public Map<String, Object> loadActiveDebugInfo(String activeid, HttpSession session) {
		try {
			ViewMode page = ViewMode.getInstance();
			ProjectActive active = projectServiceImpl.getActive(activeid);
			return page
					.putAttr("json",
							FormModelUtils.formatObjTojson(FarmJsonUtils.jsonStrToObjects(active.getLogjson())))
					.returnObjMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 获取参数变量（模板模式，带模板标签，方便用户拷贝）
	 * 
	 * @param activeid
	 * @param paras
	 * @param session
	 * @return
	 */
	@RequestMapping("/loadMarkAttrs")
	@ResponseBody
	public Map<String, Object> loadMarkAttrs(String activeid, HttpSession session) {
		try {
			ViewMode page = ViewMode.getInstance();
			List<String> paras = projectServiceImpl.getActiveTemplateMarkMap(activeid);
			String txt = "";
			for (String node : paras) {
				txt = txt + node + "\n";
			}
			return page.putAttr("json", txt).returnObjMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 指定项目实例到某个任务节点
	 * 
	 * @param activeid
	 * @param paras
	 * @param session
	 * @return
	 */
	@RequestMapping("/chooseActiveNode")
	@ResponseBody
	public Map<String, Object> chooseActiveNode(String activeid, String nodeid, HttpSession session) {
		try {
			ViewMode page = ViewMode.getInstance();
			projectServiceImpl.chooseActiveNode(activeid, nodeid, getCurrentUser(session));
			return page.returnObjMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 运行模板引擎，生成模板文件
	 * 
	 * @param activeid
	 * @param paras
	 * @param session
	 * @return
	 */
	@RequestMapping("/doRunTemplate")
	@ResponseBody
	public Map<String, Object> doRunTemplate(String activeid, String nodeid, HttpSession session) {
		try {
			ViewMode page = ViewMode.getInstance();

			Map<String, Object> attrs = projectServiceImpl.getActiveConfigerMap(activeid);
			ProjectActive active = projectServiceImpl.getActive(activeid);
			Tasknode tnode = taskNodeServiceImpl.getTasknodeEntity(active.getNodeid());
			Template template = templateServiceImpl.getTemplateEntity(tnode.getRid());
			List<TemplateDir> dirs = templateServiceImpl.getTemplateDirs(template.getId());
			Map<String, String> dirsPathMap = new HashMap<String, String>();
			// 先刪除目錄
			FreeMarkerUtils.deleteDirectory(
					new File(FreeMarkerUtils.getActiveTemplatePath(active.getId(), template.getCode())));

			Map<String, String> fileInfos = new HashMap<String, String>();

			for (TemplateDir dir : dirs) {
				List<SysDir> sysdirs = templateServiceImpl.getTemplateDir(dir, attrs);
				String path = templateServiceImpl.creatSysDir(sysdirs, active, template);
				dirsPathMap.put(dir.getId(), path);
				fileInfos.put(dir.getCode(), path);
			}
			List<TemplateFile> files = templateServiceImpl.getTemplateFiles(template.getId());
			for (TemplateFile file : files) {
				String dirPath = dirsPathMap.get(file.getDirid());
				SysFile sfile = templateFileServiceImpl.runTemplate(file, attrs);
				String filepath = templateFileServiceImpl.creatSysFile(dirPath, sfile, active, template);
				fileInfos.put(file.getFilename(), filepath);
			}

			projectServiceImpl.saveActiveParameters(activeid, "template-" + template.getCode(),
					FormModelUtils.formatObjTojson(fileInfos), getCurrentUser(session));
			// System.out.println(getTemplateString("xxx頂頂頂${emp} ", dataModel));
			return page.returnObjMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 运行生成项目
	 * 
	 * @return
	 */
	@RequestMapping("/actives")
	public ModelAndView actives(String projectid, HttpSession session, String pagemodel, HttpServletRequest request) {
		ViewMode mode = ViewMode.getInstance();
		try {
			Project project = projectServiceImpl.getProjectEntity(projectid);
			List<ProjectActive> actives = projectServiceImpl.getAllActive(projectid);
			return mode.putAttr("project", project).putAttr("actives", actives).putAttr("pagemodel", pagemodel)
					.returnModelAndView(ThemesUtil.getThemePath() + "/project/active-list");
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e)
					.returnModelAndView(ThemesUtil.getThemePath() + "/simple-500");
		}
	}

	/**
	 * 运行生成项目
	 * 
	 * @return
	 */
	@RequestMapping("/creatRun")
	public ModelAndView creatRun(String projectid, String note, String pagemodel, HttpSession session,
			HttpServletRequest request) {
		ViewMode mode = ViewMode.getInstance();
		try {
			ProjectActive active = projectServiceImpl.creatActive(projectid, note, getCurrentUser(session));
			return mode
					.returnRedirectOnlyUrl("/prorun/index.do?activeid=" + active.getId() + "&pagemodel=" + pagemodel);
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e)
					.returnModelAndView(ThemesUtil.getThemePath() + "/simple-500");
		}
	}
}
